package com.learn.security.utils.message_digest;

import com.learn.security.utils.BaseUtil;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

/**
 * HMAC加密工具类
 */
public class HMACUtil extends BaseUtil {

    public static final String KEY_MAC = "HmacMD5";

    /**
     * 初始化HMAC密钥
     *
     * @return HMAC密钥--base64加密的字符
     */
    public static String initMacKey() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);
            SecretKey secretKey = keyGenerator.generateKey();
            return encryptBASE64(secretKey.getEncoded());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * HMAC加密
     *
     * @param data 加密文件
     * @param key  秘钥--base64加密的字符
     */
    public static byte[] encryptHMAC(byte[] data, String key) {

        byte[] bytes = decryptBASE64(key);

        if (null != bytes) {
            SecretKey secretKey = new SecretKeySpec(bytes, KEY_MAC);

            try {
                Mac mac = Mac.getInstance(secretKey.getAlgorithm());
                mac.init(secretKey);
                return mac.doFinal(data);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
